package com.rgp.servicessepush.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author nhp
 * @version 1.0
 * @description TODO
 * @date 2024-04-24 20:24
 */
@RestController
public class SseController {

    public static Map<String,SseEmitter> map = new HashMap<>();

    @GetMapping("/connect/{userId}")
    public SseEmitter connect(@PathVariable("userId")String userId){
        System.out.println("用户ID[" + userId + "]建立了连接");
        SseEmitter sseEmitter = new SseEmitter(0l);
        map.put(userId,sseEmitter);
        return sseEmitter;
    }

    @GetMapping("/push")
    public String push(@RequestParam("userId") String userId,
                       @RequestParam("content") String content){
        if (map.containsKey(userId)){
            try {
                map.get(userId).send(content);
                return "给用户[" + userId + "]发送消息：" + content;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "给用户" + userId + "发送消息失败";
        }else{
            return "连接已关闭";
        }
    }

    @GetMapping("/close/{userId}")
    public String close(@PathVariable("userId") String userId){
        System.out.println("关闭连接的用户是：" + userId);
        if (map.containsKey(userId)){
            map.remove(userId);
        }
        return "close success";
    }
}